package chagine.mdt.utils;

import chagine.core.ErrorCode;
import chagine.core.exception.SeeingRuntimeException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;

public class JacksonUtil {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 生成json
     */
    public static String generateJson(Object value) {
        return generateJson(value, null);
    }

    /**
     * 生成json
     */
    public static String generateJson(Object value, String errorMessage) {
        try {
            return OBJECT_MAPPER.writeValueAsString(value);
        } catch (Exception e) {
            throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, (StringUtils.isNotBlank(errorMessage) ? errorMessage : "") + "对象转JSON转，转换异常");
        }
    }

    /**
     * json转对象
     */
    public static <T> T jsonToObj(String json, TypeReference<T> typeReference) {
        return jsonToObj(json, typeReference, null);
    }

    /**
     * json转对象
     */
    public static <T> T jsonToObj(String json, TypeReference<T> typeReference, String errorMessage) {
        try {
            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (Exception e) {
            throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, (StringUtils.isNotBlank(errorMessage) ? errorMessage : "") + "JSON转对象，转换异常");
        }
    }

}
